package com.hw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 *
 * @author whw
 * @date 2021/6/11
 */
@Component
@Slf4j
public class JwtUtils {
    /**
     * 请求头token键值
     */
    public static String tokenAuthHeader;

    /**
     * 过期时间
     */
    public static long expireTime;

    /**
     * JWT认证加密私钥(Base64加密)
     */
    public static String secret;

    @Value("${jwt.token-auth-header}")
    private void setTokenAuthHeader(String tokenAuthHeader) {
        JwtUtils.tokenAuthHeader = tokenAuthHeader;
    }

    @Value("${jwt.expire-time}")
    private void setExpireTime(long expireTime) {
        JwtUtils.expireTime = expireTime;
    }

    @Value("${jwt.secret}")
    private void setSecret(String secret) {
        JwtUtils.secret = secret;
    }

    /**
     * 生成token
     *
     * @param username 用户名
     * @return 返回的token字符串
     */
    public static String sign(String username) {
        //将当前时间的毫秒数和设置的过期时间相加生成一个新的时间
        Date date = new Date(System.currentTimeMillis() + expireTime);
        //由密钥创建一个指定的算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                //附带username信息
                .withClaim("username", username)
                //附带过期时间
                .withExpiresAt(date)
                //使用指定的算法进行标记
                .sign(algorithm);
    }

    /**
     * 验证token是否正确
     *
     * @param token    前端传过来的token
     * @param username 用户名
     * @return 返回boolean
     */
    public static boolean verify(String token, String username) {
        try {
            //获取算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //生成JWTVerifier
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            //验证token
            verifier.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            throw new TokenExpiredException("token已过期");
        } catch (JWTVerificationException e) {
            throw new JWTVerificationException("token校验失败");
        }
    }

    /**
     * 获取token中的荷载信息
     *
     * @param token
     * @param claim 荷载键
     * @return
     */
    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 刷新token过期时间
     *
     * @param token token
     * @return
     */
    public static String refreshTokenExpired(String token) {
        DecodedJWT jwt = JWT.decode(token);
        Map<String, Claim> claims = jwt.getClaims();
        try {
            Date date = new Date(System.currentTimeMillis() + expireTime);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTCreator.Builder builder = JWT.create().withExpiresAt(date);
            for (Map.Entry<String, Claim> entry : claims.entrySet()) {
                builder.withClaim(entry.getKey(), entry.getValue().asString());
            }
            return builder.sign(algorithm);
        } catch (JWTCreationException e) {
            return null;
        }
    }
}
